package com.hanbang.chu_xing_gao_zhao.module;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.application.MyApplication;
import com.hanbang.chu_xing_gao_zhao.base.BaseDataActivity;
import com.hanbang.chu_xing_gao_zhao.entity.PopupData;
import com.hanbang.chu_xing_gao_zhao.entity.UserInforData;
import com.hanbang.chu_xing_gao_zhao.myview.CircleImageView;
import com.hanbang.chu_xing_gao_zhao.myview.MorePopupWindowPublic;
import com.hanbang.chu_xing_gao_zhao.myview.MorePopupWindowPublic.OnClickCallback;
import com.hanbang.chu_xing_gao_zhao.myview.MyDialog;
import com.hanbang.chu_xing_gao_zhao.myview.MyDialog.MODE;
import com.hanbang.chu_xing_gao_zhao.utils.JsonHelper;
import com.hanbang.chu_xing_gao_zhao.utils.MyLog;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.chu_xing_gao_zhao.utils.SystemTools;
import com.hanbang.chu_xing_gao_zhao.view_city_select.CitySelectActivity;
import com.hanbang.chu_xing_gao_zhao.view_dynamic.DynamicActivity;
import com.hanbang.chu_xing_gao_zhao.view_me.VIPUserAuthentication;
import com.hanbang.chu_xing_gao_zhao.view_photo.ClipPhotoActivity;
import com.hanbang.cxgz_2.R;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class RegisterPerfectActivity extends BaseDataActivity {
	/** 肖像 */
	private CircleImageView portrait;

	/** 导航按钮-年龄 */
	private LinearLayout age;

	/** 导航按钮-城市 */
	private LinearLayout city;

	/** 导航按钮-菜系 */
	private LinearLayout styleOfCooking;

	/** 导航按钮-职位 */
	private LinearLayout position;

	/** checkBox TextView map 对象 */
	private Map<CheckBox, TextView> CTMap = new HashMap<CheckBox, TextView>();

	/** checkBoxs组 实现单选 */
	private ArrayList<CheckBox> checkBoxs = new ArrayList<CheckBox>();

	/** 性别 */
	private String gender = "";

	/** 拍完照存放的名称 */
	private String camera = "capture.jpg";

	/** VIP 认证 */
	private TextView VIPAuthentication;

	/** 注册 */
	private Button register;

	/** 城市id */
	private String cityId = "";

	/** 菜系 id */
	private String job_id = "";

	/** 图片路径 */
	private String path = "";

	Intent intent;

	/** 职位Id */
	private String positionId = "";

	/** 菜系 id */
	private StringBuffer cuisines_id = new StringBuffer();

	/** 名字 */
	private EditText name;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register_perfect_data);

		initView();
		setOnClickListener();
		addDataOnlySelect();

		positionConvert();

	}

	/**
	 * 初始化view
	 */
	private void initView() {
		age = (LinearLayout) findViewById(R.id.bar_mid_age);
		city = (LinearLayout) findViewById(R.id.register_perfect_city);
		styleOfCooking = (LinearLayout) findViewById(R.id.register_perfect_styleOfCooking);
		position = (LinearLayout) findViewById(R.id.register_perfect_position);
		portrait = (CircleImageView) findViewById(R.id.register_perfect_data_portrait);
		VIPAuthentication = (TextView) findViewById(R.id.register_perfect_VIP_anthentication);
		register = (Button) findViewById(R.id.register_perfect_register);
		name = (EditText) findViewById(R.id.register_perfect_user_name);

	}

	/**
	 * 设置点击事件
	 */
	private void setOnClickListener() {
		age.setOnClickListener(onClickListener);
		city.setOnClickListener(onClickListener);
		styleOfCooking.setOnClickListener(onClickListener);
		position.setOnClickListener(onClickListener);
		portrait.setOnClickListener(onClickListener);
		VIPAuthentication.setOnClickListener(onClickListener);
		register.setOnClickListener(onClickListener);

	}

	/**
	 * 处理监听
	 */
	@SuppressWarnings("unused")
	private OnClickListener onClickListener = new OnClickListener() {
		Intent intent = new Intent();

		@Override
		public void onClick(final View v) {
			MorePopupWindowPublic popup = null;
			switch (v.getId()) {
			// 选择年龄
			case R.id.bar_mid_age:
				popup = new MorePopupWindowPublic(RegisterPerfectActivity.this, R.layout.item_popupwindow_public,
						ageArrayList, 8);
				popup.showPopupWindow(age.getChildAt(0), 2);

				break;
			// 选择城市
			case R.id.register_perfect_city:

				intent.setClass(getApplicationContext(), CitySelectActivity.class);
				startActivityForResult(intent, 99);
				break;
			// 选择菜系
			case R.id.register_perfect_styleOfCooking:

				/**
				 * 等于1的时候下拉选择（厨师）
				 */
				if (positionId.equals("1")) {

					popup = new MorePopupWindowPublic(RegisterPerfectActivity.this, R.layout.item_popupwindow_public,
							styleOfCookingList, 8);
					popup.showPopupWindow(styleOfCooking.getChildAt(0), 3);

					/**
					 * 等于2的时候弹出对话框多选（经理）
					 */
				} else if (positionId.equals("2")) {

					MyDialog mydialog = new MyDialog(RegisterPerfectActivity.this, R.style.about_me_dialog,
							MyDialog.MODE.STYE_OF_COOKING);

					mydialog.setTitle("请选择菜系");

					mydialog.setOnClickCallback(new com.hanbang.chu_xing_gao_zhao.myview.MyDialog.OnClickCallback() {

						@Override
						public void onClick(MyDialog dialog, Object number, Object content) {
							StringBuffer sb = new StringBuffer();

							if ((Integer) number == 2) {
								// 把接收过的内容强转
								styleOfCookingList = (ArrayList<PopupData>) content;
								// 清空
								sb.delete(0, sb.length());
								cuisines_id.delete(0, cuisines_id.length());
								// 把状态是true 的id 选择出来
								for (int i = 0; i < styleOfCookingList.size(); i++) {
									if (styleOfCookingList.get(i).isSelect()) {

										cuisines_id.append(String.valueOf(styleOfCookingList.get(i).getId()));
										cuisines_id.append(",");

										sb.append(styleOfCookingList.get(i).getTitle() + ",");

									}
								}

								((TextView) findViewById(R.id.register_perfect_styleOfCooking_content)).setText(sb
										.toString());

							}

						}
					});

					mydialog.setSelectData(styleOfCookingList);

					mydialog.show();

				}
				break;
			// 选择职位
			case R.id.register_perfect_position:
				popup = new MorePopupWindowPublic(RegisterPerfectActivity.this, R.layout.item_popupwindow_public,
						positionList, 8);
				popup.showPopupWindow(position.getChildAt(0), 3);

				break;

			// VIP认证
			case R.id.register_perfect_VIP_anthentication:
				intent.setClass(getApplicationContext(), VIPUserAuthentication.class);

				startActivity(intent);
				break;

			// 更改头像
			case R.id.register_perfect_data_portrait:
				// if (isLogin(true)) {
				// } else {
				// break;
				// }

				// 新建一个dialog 对话框
				MyDialog myDialog = new MyDialog(RegisterPerfectActivity.this, R.style.about_me_dialog, MODE.HEAD);
				// 添加图片的监听
				myDialog.setOnClickCallback(new com.hanbang.chu_xing_gao_zhao.myview.MyDialog.OnClickCallback() {

					@Override
					public void onClick(MyDialog dialog, Object number, Object content) {

						// 拍照
						if ((Integer) number == 1) {
							File fDir = new File(MyApplication.picFilepath);
							if (fDir.exists() || fDir.mkdirs()) {
								File cameraFile = new File(fDir, camera);
								if (!cameraFile.exists()) {
									try {
										cameraFile.createNewFile();
									} catch (IOException e) {
										e.printStackTrace();
									}
								}
								Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
								intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
								startActivityForResult(intent, 998);
							}
							// 相册选择
						} else if ((Integer) number == 2) {
							// 获取相册
							Intent intent = new Intent();
							intent.setType("image/*");
							intent.setAction(Intent.ACTION_GET_CONTENT);
							intent.putExtra("return-data", true);
							startActivityForResult(intent, 999);
						}

					}
				});
				myDialog.show();

				break;
			// 注册
			case R.id.register_perfect_register:

				register();
				break;
			default:

				break;
			}

			// 得到菜系点击监听的处理
			if (popup != null) {

				popup.setOnClickCallback(new OnClickCallback() {

					@Override
					public void onClick(MorePopupWindowPublic morePopWindow, Object number, String content) {

						for (int i = 0; i < morePopWindow.parentView.size(); i++) {
							if ((Integer) number == i) {
								// 先把v
								// 转换成具体的容器的对象，然后再从容器对象得到第一个元素，并转换成TextView对象，然后进行赋值
								((TextView) ((LinearLayout) v).getChildAt(0)).setText(content);

								// 得到菜系id
								if (R.id.register_perfect_styleOfCooking == v.getId()) {
									cuisines_id.append(i + ",");

								}

								// 得到菜系职位
								if (R.id.register_perfect_position == v.getId()) {
									job_id = i + "";
								}

							}
						}

					}
				});
			}

		}
	};

	/**
	 * intent 的回调方法
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		/**
		 * 得到返回过来的城市
		 */
		if (requestCode == 99 && resultCode == RESULT_OK) {

			String city = data.getStringExtra("city");
			cityId = data.getStringExtra("cityId");

			((TextView) findViewById(R.id.tv_register_perfect_city)).setText(city);

		}

		/**
		 * 获取图片地址
		 */
		if (requestCode == 999 && resultCode == -1) {
			/*
			 * 相册 resultCode: 正常返回-1 用户后退返回0
			 */
			Intent intent = new Intent(RegisterPerfectActivity.this, ClipPhotoActivity.class);
			Uri uri = data.getData();
			intent.putExtra("path", SystemTools.getPath(RegisterPerfectActivity.this, uri));
			startActivityForResult(intent, 1000);
		} else if (requestCode == 1000 && resultCode == 1000) {
			/*
			 * 相片裁剪界面发过来的
			 */
			path = data.getStringExtra("path");
			bitmapUtils.display(portrait, path);

		} else if (requestCode == 998 && resultCode == -1) {
			// 拍照返回的数据
			Intent intent = new Intent(RegisterPerfectActivity.this, ClipPhotoActivity.class);
			File fDir = new File(MyApplication.picFilepath);
			if (fDir.exists() || fDir.mkdirs()) {
				File cameraFile = new File(fDir, camera);
				if (cameraFile.exists()) {
					intent.putExtra("path", cameraFile.getPath());
					startActivityForResult(intent, 1000);
				} else {
					MyToast.show(RegisterPerfectActivity.this, "获取照片失败！", Toast.LENGTH_SHORT);
				}
			} else {
				MyToast.show(RegisterPerfectActivity.this, "获取照片失败！", Toast.LENGTH_SHORT);
			}
		}

	};

	/**
	 * 添加单选数据
	 */
	private void addDataOnlySelect() {
		CTMap.put((CheckBox) findViewById(R.id.register_checkBox_1),
				(TextView) findViewById(R.id.register_checkBox_content_1));
		CTMap.put((CheckBox) findViewById(R.id.register_checkBox_2),
				(TextView) findViewById(R.id.register_checkBox_content_2));

		checkBoxs.add((CheckBox) findViewById(R.id.register_checkBox_1));
		checkBoxs.add((CheckBox) findViewById(R.id.register_checkBox_2));

	}

	/**
	 * checkBox 选择的监听一次只能选择一个选择，是单选按钮的功能
	 *
	 * @param v
	 *            :是一个ViewGroup对象,所以要先转换成具体对象容器，然后在从容器中获取具体的对象
	 */
	public void checkBoxListener(View v) {

		LinearLayout ll = (LinearLayout) v;

		for (int i = 0; i < checkBoxs.size(); i++) {

			// 把点击的控件设置为选中状态
			if (checkBoxs.get(i) == (CheckBox) ll.getChildAt(0)) {
				((CheckBox) ll.getChildAt(0)).setSelected(true);

				// 职位类型赋值（从map 通过key中获取value）
				gender = CTMap.get((CheckBox) ll.getChildAt(0)).getText().toString();
			} else {
				checkBoxs.get(i).setSelected(false);
			}

		}
		// 把中文性别抱团成id
		gender = (gender.equals("男")) ? ("1") : ("2");

	}

	/**
	 * 职位转换：把文本转换成id
	 */
	private void positionConvert() {
		intent = getIntent();
		// 把传过来的职位转换成数字
		positionId = intent.getStringExtra("position");
		if (position != null) {

			switch (positionId) {
			case "厨师":
				positionId = "1";
				break;
			// 如果是经理人下拉图标换成“加号”
			case "经理人":
				positionId = "2";
				((ImageView) findViewById(R.id.register_perfect_styleOfCooking_icon)).setImageResource(R.drawable.add);

				break;
			// 如果是其他把菜系与职位颜色变成灰色，并失去点击
			case "其他":
				positionId = "3";
				((TextView) findViewById(R.id.register_perfect_styleOfCooking_title)).setTextColor(0xff999999);
				((TextView) styleOfCooking.getChildAt(0)).setTextColor(0xff999999);
				styleOfCooking.setEnabled(false);

				((TextView) findViewById(R.id.register_perfect_position_title)).setTextColor(0xff999999);
				((TextView) position.getChildAt(0)).setTextColor(0xff999999);
				position.setEnabled(false);

				break;

			default:
				break;
			}
		}

	}

	/**
	 * 时行注册
	 *
	 * http://mrcm.hbung.com/tools/UserLogin.ashx?action=user_register&nickname=
	 * asa &mobile=19051196428&code=0532&password=123&againpassword=123 --注册
	 *
	 * telphone：手机号
	 *
	 * password0：密码
	 *
	 * password1：密码
	 *
	 * code：验证码
	 *
	 * group：类别
	 *
	 * user_name：用户名
	 *
	 * age：年龄
	 *
	 * sex：性别
	 *
	 * city_id：城市
	 *
	 * cuisines_id：菜系
	 *
	 * signfoods：擅长的菜
	 *
	 * job_id：职务
	 *
	 * avatar：头像
	 *
	 */
	private void register() throws IndexOutOfBoundsException {
		RequestParams params = new RequestParams();

		// 路径-不能为空
		if (path == "") {
			MyToast.show(RegisterPerfectActivity.this, "头像不能为空，请选择", Toast.LENGTH_LONG);
			return;
		}

		// 名字-不能为空
		// MyLog.i("text", "name:"+name.getText().toString());
		if (name.getText().toString().equals("")) {
			MyToast.show(RegisterPerfectActivity.this, "名字不能为空，请选输入", Toast.LENGTH_LONG);
			return;
		}

		// 年龄-不能为空
		// MyLog.i("text", "age:"+((TextView)
		if (((TextView) findViewById(R.id.tv_register_perfect_age)).getText().toString().equals("请选择")) {
			MyToast.show(RegisterPerfectActivity.this, "年龄不能为空，请选择", Toast.LENGTH_LONG);
			return;
		}

		// 性别-不能为空
		// MyLog.i("text", "gender:" + gender);
		if (gender == "") {
			MyToast.show(RegisterPerfectActivity.this, "性别不能为空，请选择", Toast.LENGTH_LONG);
			return;
		}

		// 城市-不能为空
		if (cityId == "") {
			MyToast.show(RegisterPerfectActivity.this, "城市不能为空，请选择", Toast.LENGTH_LONG);
			return;
		}

		// 菜系-不能为空
		if (cuisines_id.length() < 1 && !positionId.equals("3")) {
			MyToast.show(RegisterPerfectActivity.this, "菜系不能为空，请选择", Toast.LENGTH_LONG);
			return;
		}

		// 职位-不能为空
		if (job_id == "" && !positionId.equals("3")) {
			MyToast.show(RegisterPerfectActivity.this, "职位不能为空，请选择", Toast.LENGTH_LONG);
			return;
		}

		// 新建一个文件
		File file = new File(path);
		if (file.exists() && file.length() > 0) {
			params.addBodyParameter("avatar", file);
		}
		// 添加发送的参数
		params.addBodyParameter("action", "Register");
		params.addBodyParameter("telphone", intent.getStringExtra("phone"));
		params.addBodyParameter("password0", intent.getStringExtra("password0"));
		params.addBodyParameter("password1", intent.getStringExtra("password1"));
		params.addBodyParameter("code", intent.getStringExtra("code"));
		params.addBodyParameter("group", positionId);
		params.addBodyParameter("user_name", name.getText().toString());
		params.addBodyParameter("age", ((TextView) findViewById(R.id.tv_register_perfect_age)).getText().toString());
		params.addBodyParameter("sex", gender);
		params.addBodyParameter("city_id", cityId);
		params.addBodyParameter("cuisines_id", String.valueOf(cuisines_id));
		params.addBodyParameter("job_id", job_id);

		MyLog.i("text", "*000**" //
				+ "	\n手机号：" + intent.getStringExtra("phone")//
				+ "	\n密码0：" + intent.getStringExtra("password0")//
				+ "	\n密码1：" + intent.getStringExtra("password1")//
				+ "	\n验证码：" + intent.getStringExtra("code")//
				+ "	\n职位：" + job_id//
				+ "	\n职位分类：" + positionId//
				+ "	\n名字：" + ((EditText) findViewById(R.id.register_perfect_user_name)).getText().toString()//
				+ "	\n年龄：" + ((TextView) findViewById(R.id.tv_register_perfect_age)).getText().toString()//
				+ "	\n城市：" + cityId//
				+ "	\n菜系：" + cuisines_id//
				+ "	\n性别：" + gender//
		);//

		// 进行发送
		httpUtils.send(HttpMethod.POST, HttpInterfaces.Register, params,
				new MyRequestCallBack<String>(this, "正在注册...") {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(responseInfo.result);
							int status = json.getInt("Result");

							if (status == 0) {
								UserInforData userInforData = JsonHelper.parseObject(json.getJSONObject("model"),
										UserInforData.class);

								try {
									// 把用所有信息保存到数据库
									dbUtils.saveOrUpdate(userInforData);
									// 把账号与密码存入SharedPrerences中

									MySharedPreferences.setSharedPreferencesKeyAndValue(RegisterPerfectActivity.this,
											MySharedPreferences.USER_DATA, "tlephone",
                                            intent.getStringExtra("phone"));
									MySharedPreferences.setSharedPreferencesKeyAndValue(RegisterPerfectActivity.this,
											MySharedPreferences.USER_DATA, "password",
											intent.getStringExtra("password0"));

								} catch (DbException e) {

									e.printStackTrace();
								}
								// 跳转到登录界面
								Intent intent = new Intent(RegisterPerfectActivity.this, DynamicActivity.class);
								startActivity(intent);

								finish();
							} else {
								MyToast.show(RegisterPerfectActivity.this, json.getString("Msg"), Toast.LENGTH_LONG);
							}
						} catch (JSONException e) {
							e.printStackTrace();
							MyToast.show(RegisterPerfectActivity.this, "注册失败", Toast.LENGTH_LONG);
						}
					}
				});
	}

	@Override
	protected void onResume() {
		// 设置顶部的标题
		setBackArrows(findViewById(R.id.bar_top_conver_classify_back));
		setTitleMore(View.VISIBLE, View.INVISIBLE, "完善资料", null, null, null);

		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

}
